package com.gitee.sop.servercommon.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosWatch;
import com.i72.basic.BasicMarkter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Map;

/**
 * @author tanghc
 */
@Slf4j
public class ServiceConfiguration extends SpringmvcConfiguration {

    @Configuration
    @ConditionalOnClass(name = "com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration")
    class NacosConfiguration{
        @Bean
        @ConditionalOnMissingBean
        //存在spring cloud 包

        //@ConditionalOnProperty("spring.cloud.nacos.discovery.server-addr")
        public NacosWatch nacosWatch(
                NacosServiceManager nacosServiceManager,
                NacosDiscoveryProperties nacosDiscoveryProperties,
                ObjectProvider<ThreadPoolTaskScheduler> taskScheduler,
                Environment environment
        ) {
            Map<String, String> metadata = nacosDiscoveryProperties.getMetadata();
            String contextPath = environment.getProperty(METADATA_SERVER_CONTEXT_PATH);
            // 将context-path信息加入到metadata中
            if (contextPath != null) {
                metadata.put(METADATA_SERVER_CONTEXT_PATH, contextPath);
            }
            // 在元数据中新增启动时间，不能修改这个值，不然网关拉取接口会有问题
            // 如果没有这个值，网关会忽略这个服务
            metadata.put("server.startup-time", String.valueOf(System.currentTimeMillis()));
            return new NacosWatch(nacosServiceManager, nacosDiscoveryProperties, taskScheduler);
        }
    }


    @Configuration
    @ConditionalOnClass(name = "com.i72.basic.BasicConfiguration")
    class ZKConfiguration{
        @Bean
        @ConditionalOnMissingBean
        public BasicMarkter ZKManager(){
            return new BasicMarkter();
        }
    }

}
